/**
 * 
 */
package com.cipe.cmrs.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cipe.cmrs.model.Country;
import com.cipe.cmrs.model.Region;
import com.cipe.cmrs.model.User;
import com.cipe.cmrs.util.DateUtil;
import com.cipe.cmrs.util.UserUtil;

/**
 * @author Incepio
 * 
 */
@Service
@Transactional
public class CountryService extends BaseService<Country> {

	@Autowired
	private UserService	userService;
	
    @Autowired RegionService regionService;
	
    public Country saveCountry(Country country, Integer userId) {
		if (country != null) {
			User user = UserUtil.INSTANCE.getCurrentUser();
			Country dbCountry = findById(country.getId());
			if (dbCountry == null) {
				dbCountry = new Country();
				dbCountry.setCreatedBy(user);
				dbCountry.setCreationDate(DateUtil.getCurrentDate());
			}
			
			Region region = country.getRegion();
			if (null != region) {
				dbCountry.setRegion(region);
			}			
			dbCountry.setProgramOfficer(country.getProgramOfficer());
			dbCountry.setProgramAssistant(country.getProgramAssistant());
			dbCountry.setDisplayName(country.getDisplayName());
			dbCountry.setUpdatedBy(user);
			dbCountry.setUpdationDate(DateUtil.getCurrentDate());
			return merge(dbCountry);
		}
		return null;
	}
	
	public List<Country> getAllCountries() {
		return dao.getResultList("FROM Country ORDER BY displayName ASC");
	}
	
	public List<Country> getAllCountriesByRegion(Integer regionId) {
		return dao.getResultList("FROM Country where region.id="+regionId+" ORDER BY displayName ASC");
	}
}
